<?php
/**
 * Created by PhpStorm.
 * User: 1
 * Date: 2016-10-20
 * Time: 15:27
 */

namespace app\src\shoppingCart\action;

use app\src\base\exception\BusinessException;
use app\src\base\helper\ValidateHelper;
use app\src\category\logic\SkuLangLogic;
use app\src\category\logic\SkuvalueLangLogic;
use app\src\goods\helper\PriceHelper;
use app\src\goods\logic\ProductLogic;
use app\src\goods\logic\ProductSkuLogic;
use app\src\base\action\BaseAction;
use app\src\shoppingCart\helper\ShoppingCartCheckHelper;
use app\src\shoppingCart\logic\ShoppingCartLogic;
use app\src\shoppingCart\model\ShoppingCart;

class ShoppingCartAddAction extends BaseAction
{
    /**
     * 1. 库存是否足够
     * 2. 最小起订量是否满足
     * 3. 最大限购数量是否满足
     *
     * @param $detail
     * @param $sku
     * @param $count
     * @return bool|mixed
     */
    private function check($detail,$sku,$count){

        if($count > $sku['quantity']){
            return lang('err_cart_quantity',['quantity'=>$sku['quantity']]);
        }

        $check_status = [
            'onshelf'=>$detail['onshelf'],
            'quantity'=>$sku['quantity'],
            'expire_time'=>$detail['expire_time']
        ];

        $item_status = ShoppingCartCheckHelper::check($check_status,$count);

        if($item_status != ShoppingCart::CART_STATUS_NORMAL){
            return ShoppingCart::getCartStatusDesc($item_status);
        }
        
        return false;
    }

    /**
     * 加入购物车
     * @param $entity
     * @return array
     */
    public function add($entity,$lang){
        $uid = $entity['uid'];
        $id = $entity['id'];

        $count = $entity['count'];
        $sku_pkid = $entity['sku_pkid'];

        //TODO: uid,id是否合法的验证

        $logic = new ProductSkuLogic();
        $productLogic = new ProductLogic();
        $result = $productLogic->detail($id,$lang);
        
        if(!$result['status']){
            return $this->error($result['info']);
        }

        if(empty($result['info'])){
            return $this->error(lang('err_cart_invalid_sku_pkid'));
        }

        $detail = $result['info'];
        $cur_sku = [];
        foreach ($detail['sku_list'] as $sku){
            if($sku['sku_pkid'] == $sku_pkid){
                $cur_sku = $sku;
                break;
            }
        }

        if(count($cur_sku) == 0){
            return $this->error(lang('err_cart_invalid_sku_pkid'));
        }

        $check_result = $this->check($detail,$cur_sku,$count);
        if($check_result !== false){
            return $this->error($check_result);
        }
        
        $price = PriceHelper::getSkuPrice($cur_sku,$count);
        $now_time = time();
        $icon_url = $cur_sku['icon_url'];
        if(empty($icon_url)){
            $icon_url = $detail['main_img'];
        }
        $sku_desc = "";
        if($lang != "zh-cn"){
            $sku_desc = $this->translate($cur_sku['sku_id'],$lang);
        }

        if(empty($sku_desc)){
            $sku_desc = $cur_sku['sku_desc'];
        }

        $item = [
            'uid'=>$uid,
            'create_time'=>$now_time,
            'update_time'=>$now_time,
            'store_id'=>$detail['store_id'],
            'p_id'=>$id,
//            'product_code'=>$detail['product_code'],
            'sku_id'=>$cur_sku['sku_id'],
            'sku_desc'=>$sku_desc,
            'icon_url'=>$icon_url,
            'count'=>$count,
            'name'=>$detail['name'],
            'express'=>0,
            'template_id'=>$detail['template_id'],
            'price'=>$price,
            'ori_price'=>$cur_sku['ori_price'],
            'psku_id'=>$cur_sku['sku_pkid'],
            'weight'=>$detail['weight'],
            'tax_rate'=>0,
            'group_id'=>0,
            'package_id'=>0
        ];

        $logic  = new ShoppingCartLogic();

        $result = $logic->getInfo(['p_id'=>$id,'uid'=>$uid,'psku_id'=>$cur_sku['sku_pkid']]);

        if(ValidateHelper::legalArrayResult($result)){

            //更新
            $info = $result['info'];
            $item['count'] = intval($item['count']) + intval($info['count']);

            //计算 price
            $item['price'] = PriceHelper::getSkuPrice($cur_sku,$item['count']);

            unset($item['create_time']);
            $result = $logic->save(['id'=>$info['id']],$item);
        }else{
            //增加
            $result = $logic->add($item);
        }
        return $this->result($result);
    }

    private function translate($sku_ids,$lang){
        $sku_arr = explode(";",$sku_ids);

        $sku_ids = "";
        $sku_value_ids = "";
        foreach ($sku_arr as $item){
            if(!empty($item) && strpos($item,":") >= 0){
                list($sku_id,$skuvalue_id) = explode(":",$item);
                $sku_ids .= $sku_id.',';
                $sku_value_ids.=$skuvalue_id.',';
            }
        }

        $result = (new SkuLangLogic())->queryNoPaging(['sku_id'=>['in',$sku_ids],'lang'=>$lang]);
        if($result['status']){
            $skuLang = $result['info'];
        }

        $result = (new SkuvalueLangLogic())->queryNoPaging(['skuvalue_id'=>['in',$sku_value_ids],'lang'=>$lang]);
        if($result['status']){
            $skuvalueLang = $result['info'];
        }
        $sku_desc = "";
        foreach ($sku_arr as $item){
            if(!empty($item) && strpos($item,":") >= 0){
                list($sku_id,$skuvalue_id) = explode(":",$item);

                foreach ($skuLang as $one){
                    if($one['sku_id'] == $sku_id){
                        $sku_desc .= $one['name'].':';
                    }
                }
                foreach ($skuvalueLang as $two){
                    if($two['skuvalue_id'] == $skuvalue_id){
                        $sku_desc .= $two['name'].';';
                    }
                }
            }
        }

        return $sku_desc;
    }
}